import React, { Component } from "react";
import { Row, Col, Space, Tooltip, Card } from "antd";
import ItemBox from "./ItemBox";
import { ArrowRightOutlined,CopyOutlined } from "@ant-design/icons";
import ItemSelector from "./ItemSelector";
import ItemStack from "../entity/ItemStack";
import { Input } from 'antd';
import { InputNumber,Button } from 'antd';
import { Select } from 'antd';
import { message } from 'antd';
import { Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
const fs = window.require("fs");

const { Option } = Select;
const { TextArea } = Input;

/**
 * 合成台组件
 */
class CraftTable extends Component {
  constructor(props) {
    super(props);
    let itemList = [];//0为输出框，1~9为原料框
    for (let i = 0; i <= 9; i++) {
      itemList.push(new ItemStack());//默认为1个<minecraft:air>
    }
    this.state = {
      isItemSelectorVisible: false,
      itemList: itemList,//存储物品id
      curIndex:-1,//当前选择的物品框下标，-1为未选择
      recipeName:'new recipe',//配方名称
      recipeType:0,//配方类型，0-无序，1-有序，2-镜像有序
      zenscript:'',
    };

    
    
  }

  /**
   * 打开物品选择器
   * @param {int} index 当前选中的物品框下标
   */
  openItemSelector = (index) => this.setState({ isItemSelectorVisible: true ,curIndex:index});

  closeItemSelector = () => this.setState({ isItemSelectorVisible: false });

  /**
   * 选择物品的回调函数
   * @param {ItemStack} item 物品
   */
  onSelectItem = (item) => {
    if(this.state.curIndex===-1) return;//未选择物品框
    let itemList = this.state.itemList;
    itemList[this.state.curIndex] = item;
    console.log(item);
    this.setState({
      isItemSelectorVisible:false,
      itemList:itemList,
    },()=>{
      console.log(this.state.itemList);
    })
  };

  /**
   * 修改配方名称回调
   * @param {*} e 
   */
  onRecipeInputChange=(e)=>{

    this.setState({
			recipeName:e.target.value
		})
  }

  /**
   * 修改成品数目回调
   * @param {*} value
   */
  onAmountInputChange=(value)=>{
    let itemList = this.state.itemList;
    itemList[0].amount = value;
    this.setState({
			itemList:itemList
		});
  }

  /**
   * 配方类型回调
   * @param {*} value 
   */
  onRecipeTypeChange=(value)=>{
    this.setState({
      recipeType:value
    })
  }

  /**
   * 生成配方的脚本
   */
  createRecipeZenScript=()=>{
    if(!this.state.recipeName){
      //未输入配方名
      message.error('请输入配方名');
      return;
    }

    
    let zenscript = '';
    
    let outputItemStr = this.state.itemList[0].toString();
    if(this.state.itemList[0].amount!==1) outputItemStr += '*'+ this.state.itemList[0].amount;
    let a = this.state.itemList;
    let ingredients=`[${a[1]},${a[2]},${a[3]}],[${a[4]},${a[5]},${a[6]}],[${a[7]},${a[8]},${a[9]}]`;
    switch(this.state.recipeType){
      case 0:default://无序
        let ingredientsList = [...this.state.itemList]
        ingredientsList.splice(0,1)
        ingredients = ingredientsList.join(',')
        zenscript = `craftingTable.addShapeless("${this.state.recipeName}",${outputItemStr},[${ingredients}]);`
        break;
      case 1://有序
        zenscript = `craftingTable.addShaped("${this.state.recipeName}",${outputItemStr},[${ingredients}]);`
        break;

      case 2://有序镜像
        zenscript = `craftingTable.addShapedMirrored("${this.state.recipeName}",${outputItemStr},[${ingredients}]);`
        break;
    }
    this.setState({
      zenscript:zenscript
    });

  }

  /**
   * 复制按钮回调
   */
  onCopy=(e)=>{

  }

  /**
   * 选择图片组件的属性
   */
  uploadProps = {
    action: '',
    beforeUpload:(file)=> {
      const fileName = 'itemsData.json';
      
      return new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          let dataurl = reader.result;
          //将dataurl写入配置文件itemsData.json中
          //modName默认设置为'minecraft'
          let itemName = file.name.substring(0,file.name.indexOf("."));
          let data = fs.readFileSync(fileName);
          let jsonObject = JSON.parse(data);

          let importModName = 'import'
          jsonObject[importModName] = jsonObject[importModName] ?? {}
          jsonObject[importModName][itemName] = {};
          jsonObject[importModName][itemName]['texture']=dataurl;
          message.info(`物品${itemName}的材质dataUrl已经被添加到itemsData.json中，默认导入到mod“${importModName}”下，可自行修改`)
          let outputData = JSON.stringify(jsonObject,null,2);
          fs.writeFileSync(fileName,outputData);
        };
        
      });
    },
  };

  render() {
    return (
      <div>
        <ItemSelector
          visible={this.state.isItemSelectorVisible}
          onSelectItem={this.onSelectItem}
          onCancel={this.closeItemSelector}
        />
        <Row>
          <label>配方名称</label>
          <Input size="small" value={this.state.recipeName} onChange={this.onRecipeInputChange}/>
        </Row>
        <br/>
        <Row>
          <Space>
            <Col>
              <ItemBox
                key={1}
                itemStack={this.state.itemList[1]}
                onClick={()=>this.openItemSelector(1)}
              />
            </Col>
            <Col>
              <ItemBox
                key={2}
                itemStack={this.state.itemList[2]}
                onClick={()=>this.openItemSelector(2)}
              />
            </Col>
            <Col>
              <ItemBox
                key={3}
                itemStack={this.state.itemList[3]}
                onClick={()=>this.openItemSelector(3)}
              />
            </Col>
          </Space>
        </Row>
        <br />
        <Row>
          <Space>
            <Col>
              <ItemBox
                key={4}
                itemStack={this.state.itemList[4]}
                onClick={()=>this.openItemSelector(4)}
              />
            </Col>
            <Col>
              <ItemBox
                key={5}
                itemStack={this.state.itemList[5]}
                onClick={()=>this.openItemSelector(5)}
              />
            </Col>
            <Col>
              <ItemBox
                key={6}
                itemStack={this.state.itemList[6]}
                onClick={()=>this.openItemSelector(6)}
              />
            </Col>
            <Col>
            {/**装饰用 */}
              <ItemBox
                key={10}
                itemStack={new ItemStack('','')}
                icon={<ArrowRightOutlined />}
              />
            </Col>
            <Col>
            {/* 成品框 */}
              <ItemBox
                key={0}
                itemStack={this.state.itemList[0]}
                onClick={()=>this.openItemSelector(0)}
              />
            </Col>
          </Space>
        </Row>
        <br />
        <Row>
          <Space>
            <Col>
              <ItemBox
                key={7}
                itemStack={this.state.itemList[7]}
                onClick={()=>this.openItemSelector(7)}
              />
            </Col>
            <Col>
              <ItemBox
                key={8}
                itemStack={this.state.itemList[8]}
                onClick={()=>this.openItemSelector(8)}
              />
            </Col>
            <Col>
              <ItemBox
                key={9}
                itemStack={this.state.itemList[9]}
                onClick={()=>this.openItemSelector(9)}
              />
            </Col>
            <Col>
              <Tooltip title="成品数目">
                <InputNumber min={1} defaultValue={1} size="small" onChange={this.onAmountInputChange}/>
              </Tooltip>
            </Col>
          </Space>
        </Row>
        <br/>
        <Row>
          <label>配方类型：</label>
          <Select defaultValue={0} style={{ width: 120 }} onChange={this.onRecipeTypeChange}>
            <Option value={0}>无序</Option>
            <Option value={1}>有序</Option>
            <Option value={2}>有序镜像</Option>
          </Select>
          
        </Row>
        <br/>
        <Row>
          <Space>
            <Col>
              <Button type="primary" shape="round" onClick={this.createRecipeZenScript}>
              合成
              </Button>
            </Col>
            <Col>
              <Button id='copy' type="primary" shape="round" icon={<CopyOutlined/>}onClick={this.onCopy}>
              复制脚本
              </Button>
            </Col>
            <Col>
            <Upload {...this.uploadProps} multiple>
              <Button icon={<UploadOutlined /> }>导入物品材质为dataUrl</Button>
            </Upload>
            </Col>
          </Space>
        </Row>
        <br/>
        <Card >
          {this.state.zenscript}
        </Card>
      </div>
    );
  }
}

export default CraftTable;
